<template>
  <a-modal
    :title="data.departmentId && '编辑课表'||'新增课表'"
    centered
    :visible="true"
    width="1000"
    @cancel="dialogClosed"
  >
    <div style="width:1000px">
      <a-steps :current="current">
        <a-step title="设置基本信息" />
        <a-step title="设置任课老师" />
        <a-step title="编辑课表" />
      </a-steps>
      <div v-show="current === 0">
        <a-form
          :form="form0"
        >
          <br> <br>
          <a-row>
            <a-col :span="12" :offset="6">
              <a-form-item label="学年" class="label-width-auto" v-bind="formItemLayout">
                <a-select
                  v-decorator="[
                    'schoolYear',
                    { rules: [{ required: true, message: '请选择' }] },
                  ]"
                  placeholder="请选择"
                >
                  <a-select-option
                    v-for="item in schoolYearList"
                    :key="item"
                    :value="item"
                  >
                    {{ item }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12" :offset="6">
              <a-form-item label="学期" class="label-width-auto" v-bind="formItemLayout">
                <a-select
                  v-decorator="[
                    'term',
                    { rules: [{ required: true, message: '请选择' }] },
                  ]"
                  placeholder="请选择"
                >
                  <a-select-option value="第一学期">第一学期</a-select-option>
                  <a-select-option value="第二学期">第二学期</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>

          <a-row>
            <a-col :span="12" :offset="6">
              <a-form-item label="年级" class="label-width-auto" v-bind="formItemLayout">
                <a-select
                  v-decorator="[
                    'gradeId',
                    { rules: [{ required: true, message: '请选择' }] },
                  ]"
                  placeholder="请选择"
                  @change="handleGradeChange"
                >
                  <a-select-option
                    v-for="item in gradeList"
                    :key="item.deptId"
                    :value="item.deptId"
                  >
                    {{ item.deptName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12" :offset="6">
              <a-form-item label="班级" class="label-width-auto" v-bind="formItemLayout">
                <a-select
                  v-decorator="[
                    'classId',
                    { rules: [{ required: true, message: '请选择' }] },
                  ]"
                  placeholder="请选择"
                >
                  <a-select-option
                    v-for="item in subClassList"
                    :key="item.deptId"
                    :value="item.deptId"
                  >
                    {{ item.deptName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div v-show="current === 1">
        <a-form
          :form="form1"
        >
          <br> <br>
          <a-row v-for="(teacher, index) in dataForm.teachers" :key="index" type="flex" justify="space-around" align="middle">
            <a-col :span="10" :offset="1">
              <a-form-item label="科目" class="label-width-auto" v-bind="formItemLayout">
                <a-select
                  v-decorator="[
                    `teachers[${index}].courseId`,
                    { rules: [{ required: true, message: '请选择' }],
                      initialValue : dataForm.teachers[index].courseId || null},
                  ]"
                  placeholder="请选择"
                >
                  <a-select-option
                    v-for="item in courseList"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="10">
              <a-form-item label="老师" class="label-width-auto" v-bind="formItemLayout">
                <a-select
                  v-decorator="[
                    `teachers[${index}].staff`,
                    { rules: [{ required: true, message: '请选择' }],
                      initialValue : dataForm.teachers[index].staff},
                  ]"
                  label-in-value
                  show-search
                  :default-active-first-option="false"
                  :filter-option="false"
                  :not-found-content="null"
                  :show-arrow="false"
                  placeholder="请输入"
                  @search="handleSearchTeacher"
                >
                  <a-select-option
                    v-for="item in staffList"
                    :key="item.userId"
                    :value="item.userId"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>

            </a-col>
            <a-col :span="3">
              <a-icon v-if="index === 0" type="plus-circle" style="cursor:pointer" @click="handleAdd(dataForm.teachers)" />
              <a-icon v-if="index !== 0" type="minus-circle" style="cursor:pointer" @click="handleDel(dataForm.teachers, index)" />
            </a-col>
          </a-row>

        </a-form>
      </div>
      <div v-show="current === 2">
        <a-form
          :form="form2"
        >
          <br> <br>
          <table border="1" cellpadding="10" style="width:100%;text-align:center">
            <thead>
              <tr>
                <th colspan="9">{{ dataForm.schoolYear }}{{ dataForm.term }}{{ dataForm.gradeName }}{{ dataForm.className }}</th>
              </tr>
              <tr>
                <th style="width: 80px;" />
                <th v-for="(item, index) in weekDays" :key="index" style="width: 80px;">{{ item.desc }}</th>
                <th style="width: 80px;" v>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(teacher, tindex) in dataForm.details" :key="tindex">
                <td>
                  <a-form-item>
                    <a-select
                      v-decorator="[
                        `details[${tindex}].typeId`,
                        { rules: [{ required: true, message: '请选择' }],
                          initialValue : dataForm.details[tindex].typeId},
                      ]"
                      placeholder="请选择"
                    >
                      <a-select-option
                        v-for="item in typeList"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </td>
                <td v-for="(item, index) in weekDays" :key="index">
                  <a-form-item>
                    <a-select
                      v-decorator="[
                        `details[${tindex}].details[${index}].courseId`,
                        { initialValue : dataForm.id && dataForm.details[tindex].details[index].courseId || null},
                      ]"
                      :allow-clear="true"
                      placeholder="课程"
                      @change="changeCourse(tindex,index)"
                    >
                      <a-select-option
                        v-for="citem in courseList"
                        :key="citem.id"
                        :value="citem.id"
                      >
                        {{ citem.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item>
                    <a-select
                      v-decorator="[
                        `details[${tindex}].details[${index}].staff`,
                        { initialValue : dataForm.id && dataForm.details[tindex].details[index].staff || null},
                      ]"
                      :allow-clear="true"
                      label-in-value
                      placeholder="老师"
                      @focus="filterTeacher(tindex,index)"
                    >
                      <a-select-option
                        v-for="citem in currentTeacherList"
                        :key="citem.staffId"
                        :value="citem.staffId"
                      >
                        {{ citem.staffName }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </td>
                <td>
                  <a-icon v-if="tindex === 0" type="plus-circle" style="cursor:pointer" @click="handleAdd(dataForm.details)" />
                  <!--                  <a-icon v-if="tindex !== 0" type="arrow-up" style="cursor:pointer" @click="handleUp(timetableRows, index)" />-->
                  <!--                  <a-icon v-if="tindex !==  timetableRows.length" type="arrow-down" style="cursor:pointer" @click="handleDown(timetableRows, index)" />-->
                  <a-icon v-if="tindex !== 0" type="minus-circle" style="cursor:pointer" @click="handleDel(dataForm.details, index)" />

                </td>
              </tr>
            </tbody>
          </table>

        </a-form>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <a-button @click="dialogClosed()">取消</a-button>
      <a-button
        v-if="current>0"
        style="margin-left: 8px"
        @click="prev"
      >
        上一步
      </a-button>
      <a-button
        v-if="current < 2"
        type="primary"
        @click="next"
      >
        下一步
      </a-button>
      <a-button
        v-if="current == 2"
        id="submit"
        :loading="submitButton.status"
        type="primary"
        @click="dataFormSubmit()"
      >
        {{ submitButton.text }}
      </a-button>
    </span>
  </a-modal>
</template>
<style lang="less" scoped>
  .ant-form-item{
    margin-bottom: 5px;
  }
</style>

<script>
import { edit, get, getCourse, getType } from '@/pages/timetable/api/timetableIndex'
import { getStaff, schoolYearFunc } from '@/utils/department'
import formItem from '@/config/formItemLayout'
export default {
  name: 'TimetableSave',
  props: {
    data: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data () {
    return {
      current: 0,
      form0: this.$form.createForm(this, { onValuesChange: this.onValuesChange }),
      form1: this.$form.createForm(this, { onValuesChange: this.onValuesChange }),
      form2: this.$form.createForm(this, { onValuesChange: this.onValuesChange }),
      formItemLayout: formItem,
      dataForm: {
        id: null,
        teachers: [{}],
        details: [{}]
      },
      departmentList: [],
      staffList: [],
      submitButton: {
        text: '提交',
        status: false
      },
      schoolYearList: [],
      gradeList: [],
      classList: [],
      subClassList: [],
      teachers: [{}],
      details: [],
      courseList: [],
      typeList: [],
      weekDays: [{ weekDay: 2, desc: '星期一' },
        { weekDay: 3, desc: '星期二' },
        { weekDay: 4, desc: '星期三' },
        { weekDay: 5, desc: '星期四' },
        { weekDay: 6, desc: '星期五' },
        { weekDay: 7, desc: '星期六' },
        { weekDay: 1, desc: '星期日' }],
      timetableRows: [{}],
      currentTeacherList: []
    }
  },
  mounted () {
    this.schoolYearList = schoolYearFunc()
    this.$gradeListFunc().then(data => {
      this.gradeList = data
    })
    this.$classListFunc().then(data => {
      this.classList = data
      this.subClassList = data
    })

    this.$departmentListFunc().then(data => {
      this.departmentList = data
    })
    if (this.data.id) {
      this.$ajaxSend(get, this.data.id, {
        success: (data) => {
          this.dataForm = data
          this.timetableRows = []
          this.teachers = []
          this.dataForm.details.forEach((detail, tindex) => {
            this.timetableRows.push({})
            detail.details.forEach((weekDayDetail, index) => {
              weekDayDetail.staff = {
                key: weekDayDetail.staffId || null,
                label: weekDayDetail.staffName || null
              }
            })
          })
          this.dataForm.teachers.forEach((detail, tindex) => {
            detail.staff = {
              key: detail.staffId,
              label: detail.staffName
            }
            this.teachers.push({
              key: detail.staffId,
              label: detail.staffName,
              courseId: detail.courseId
            })
          })
          console.log('this.dataForm', this.dataForm)
          this.$initForm(this.form0, this.dataForm)
          this.$initForm(this.form1, this.dataForm)
          this.$initForm(this.form2, this.dataForm)
        }
      })
    }
  },
  methods: {
    dialogClosed () {
      this.$emit('dialogClosed')
    },
    // 表单提交
    dataFormSubmit () {
      this.$saveQuit('form2', edit(this.dataForm.id), (data) => {
        Object.assign(this.dataForm, data)
        this.gradeList.forEach(grade => {
          if (grade.deptId === this.dataForm.gradeId) {
            this.dataForm.gradeName = grade.deptName
          }
        })
        this.classList.forEach(classItem => {
          if (classItem.deptId === this.dataForm.classId) {
            this.dataForm.className = classItem.deptName
          }
        })
        this.dataForm.details.forEach((detail, tindex) => {
          this.typeList.forEach(type => {
            if (detail.typeId === type.id) {
              detail.typeName = type.name
              detail.isDefault = type.isDefault
            }
          })
          detail.sort = tindex
          detail.details.forEach((weekDayDetail, index) => {
            weekDayDetail.weekDay = this.weekDays[index].weekDay
            weekDayDetail.staffId = weekDayDetail.staff && weekDayDetail.staff.key || null
          })
        })
        return this.dataForm
      })
    },
    onValuesChange (props, value) {
      if (value.gradeId) {
        this.subClassList = this.classList.filter(o => o.deptPid === value.gradeId)
        this.gradeList.forEach(grade => {
          if (grade.deptId === value.gradeId) {
            this.dataForm.departmentId = grade.deptPid
          }
        })
      }
    },
    handleSelectFilter (v, o) {
      return (
        o.componentOptions.children[0].text.toLowerCase().indexOf(v.toLowerCase()) >= 0
      )
    },
    next () {
      this['form' + this.current].validateFields((err, values) => {
        if (!err) {
          Object.assign(this.dataForm, values)
          if (this.current === 0) {
            if (this.dataForm.departmentId) {
              this.$ajaxSend(getCourse, this.dataForm.departmentId, {
                success: (data) => {
                  this.courseList = data.records
                }
              })
              this.$ajaxSend(getType, this.dataForm.departmentId, {
                success: (data) => {
                  this.typeList = data.records
                }
              })
            }
          } else if (this.current === 1) {
            this.dataForm.teachers.forEach(teacher => {
              teacher.staffId = teacher.staff.key
              teacher.staffName = teacher.staff.label && teacher.staff.label.trim() || ''
            })
          }
          this.current++
        }
      })
    },
    prev () {
      this.current--
    },
    handleAdd (teachers) {
      teachers.push({})
    },
    handleDel (list, index) {
      list.splice(index, 1)
    },
    handleUp (list, index) {
      const tmp = list[index]
      list[index] = list[index - 1]
      list[index - 1] = tmp
    },
    handleDown (list, index) {
      const tmp = list[index]
      list[index] = list[index + 1]
      list[index + 1] = tmp
    },
    handleSearchTeacher (value) {
      const data = {}
      if (value - 0 > 0) {
        data.jobNumber = value
      } else {
        data.name = value
      }
      this.$ajaxSend(getStaff, data, {
        success: datas => {
          this.staffList = datas.records.filter(data => data.userId)
        }
      })
    },
    handleChangeTeacher (value) {
      console.log(value.label.trim())
    },
    filterTeacher (tindex, index) {
      const courseId = this.form2.getFieldValue(`details[${tindex}].details[${index}].courseId`)
      if (courseId) {
        this.currentTeacherList = this.dataForm.teachers.filter(teacher => teacher.courseId === courseId)
      } else {
        this.currentTeacherList = this.dataForm.teachers
      }
    },
    handleGradeChange () {
      this.form0.setFieldsValue({ classId: null })
    },
    changeCourse (tindex, index) {
      setTimeout(() => {
        const courseId = this.form2.getFieldValue(`details[${tindex}].details[${index}].courseId`)
        const staffId = this.form2.getFieldsValue([`details[${tindex}].details[${index}].staffId`])
        const filterTeachers = this.dataForm.teachers.filter(teacher => teacher.courseId === courseId)
        if (filterTeachers.length) {
          staffId.details[tindex].details[index].staff = { key: filterTeachers[0].staffId, label: filterTeachers[0].staffName }
          this.form2.setFieldsValue(staffId)
        }
      }, 10)
    }
  }
}
</script>
